<template>
  <div>
    <el-table :data="state.allUsers" ref="roleUserTable" tooltip-effect="dark" border style="width: 100%" @selection-change="handleSelectionChange" >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="用户姓名" prop="name"></el-table-column>
    </el-table>
    <div class="mt_5 tac">
      <el-button type="primary" size="default" @click="saveUserRole">确定</el-button>
    </div>
  </div>
</template>

<script setup name="roleUser">
import request from '/@/utils/request';
import { ElMessage } from 'element-plus';
import {reactive, ref, onMounted, defineProps, defineEmits, nextTick} from "vue";

const roleUserTable = ref(null)
let props = defineProps({
  roleId : {type : Number, default: 0}
})
const state = reactive({
  allUsers :[],
  selectUsers:[],
})

const handleSelectionChange = (selectRows)=>{
  state.selectUsers = selectRows
}
const saveUserRole = ()=>{
  let roleUsers = [];
  state.selectUsers.forEach((r)=>{
    roleUsers.push(r.id)
  })
  request({
    url: '/sys/role/saveuserrole',
    data: {roleId : props.roleId, roleUsers:roleUsers}
  }).then(res=>{
    if(res.code === '200'){
      ElMessage.success(res.msg)
    }
  })
}
const loadUserRole = ()=>{
  request({
    url: '/sys/role/listroleuser',
    data: {roleId : props.roleId}
  }).then(res => {
    const { data } = res
    state.allUsers = data.allUsers
    nextTick(()=>{
      state.allUsers.forEach((item)=>{
        if(data.roleUsers.filter((u)=> u.id === item.id).length > 0){
          roleUserTable && roleUserTable.value.toggleRowSelection(item, true)
        }
      })
    })
  })
}

onMounted(()=>{
  loadUserRole();
})
</script>

<style scoped>
</style>
